package cn.kgc.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.kgc.base.SystemConstant;
import cn.kgc.entity.DataDictionary;
import cn.kgc.excpetion.GraceException;
import cn.kgc.grace.result.ResponseStatusEnum;
import cn.kgc.mapper.DataDictionaryMapper;
import cn.kgc.service.DataDictionaryService;
import cn.kgc.utils.PagedGridResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;



@Slf4j
@Service("dataDictionaryService")
@SuppressWarnings("all")
public class DataDictionaryServiceImpl extends ServiceImpl<DataDictionaryMapper, DataDictionary> implements DataDictionaryService {

    @Override
    public List<DataDictionary> queryDataDictionaryByTypeAndItemKey(List<String> itemKeys) {
        return getBaseMapper().selectDataDictionaryByItemKey(itemKeys);
    }

    @Override
    public List<DataDictionary> queryDataDictionaryByType(String type) {
        LambdaQueryWrapper<DataDictionary> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(DataDictionary::getTypeCode,type);
        queryWrapper.eq(DataDictionary::getEnable, SystemConstant.DATA_DICTIONARY_ENABLE);
        return list(queryWrapper);
    }

    @Override
    public boolean deleteById(String id) {
        DataDictionary dataDictionary = getById(id);
        if(dataDictionary.getEnable()==0){
            //如果数据字典被禁用,可以被删除
            return removeById(id);
        }
        //如果数据字典被启用,不能被删除
        GraceException.display(ResponseStatusEnum.DATA_DICTIONARY_DELETE_ERROR);
        return false;
    }

    @Override
    public PagedGridResult page(int pageIndex, int pageSize, String typeName, String itemKey) {
        //查询条件
        LambdaQueryWrapper<DataDictionary> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.likeRight(
                StrUtil.isNotBlank(typeName),
                DataDictionary::getTypeName,
                typeName
        );
        queryWrapper.likeRight(
                StrUtil.isNotBlank(itemKey),
                DataDictionary::getItemKey,
                itemKey
        );
        //先按照typeName进行升序排列,如果typeName相同就按照sort进行排序
        queryWrapper.orderByAsc(DataDictionary::getTypeName,DataDictionary::getSort);
        //分页条件
        Page pageParam=new Page(pageIndex,pageSize);
        //查询+排序+分页
        page(pageParam,queryWrapper);
        //封装返回结果
        return PagedGridResult.setterPagedGrid(pageParam);
    }
}
